﻿using NAudio.CoreAudioApi;
using NAudio.Lame;
using NAudio.Wave;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;

namespace QingYun.TtsRecorder
{
    public class NAudioTTSPlayer
    {
        // 使用ManualResetEvent同步播放完成状态
        private static ManualResetEvent _playbackCompletedEvent = new ManualResetEvent(false);

        // 生成音频流（独立方法）
        private static MemoryStream GenerateAudioStream(string text, int sampleRate, int bitsPerSample, int channels)
        {
            var memoryStream = new MemoryStream();
            using (var synth = new SpeechSynthesizer())
            {
                var format = new SpeechAudioFormatInfo(
                    sampleRate,
                    (AudioBitsPerSample)bitsPerSample,
                    (AudioChannel)channels);

                synth.SetOutputToAudioStream(memoryStream, format);
                synth.Speak(text);
            }
            memoryStream.Position = 0;
            return memoryStream;
        }

        // 播放TTS语音（可控制采样率/位深）
        public static void PlayText(string text, int sampleRate = 44100, int bitsPerSample = 16, int channels = 1)
        {
            // 1. 使用System.Speech生成内存流
            // 生成内存流
            var memoryStream = GenerateAudioStream(text, sampleRate, bitsPerSample, channels);

            // 2. 使用NAudio播放

            // 配置音频流
            using (var waveStream = new RawSourceWaveStream(memoryStream, new WaveFormat(sampleRate, bitsPerSample, channels)))
            {
                // 使用WASAPI输出
                using (var wasapiOut = new WasapiOut(AudioClientShareMode.Shared, 100))
                {
                    // 订阅播放完成事件
                    wasapiOut.PlaybackStopped += (sender, e) =>
                    {
                        _playbackCompletedEvent.Set(); // 通知播放完成
                    };

                    wasapiOut.Init(waveStream);
                    wasapiOut.Play();

                    // 等待播放完成（非阻塞方式）
                    _playbackCompletedEvent.WaitOne();
                    _playbackCompletedEvent.Reset();
                }
            }
        }

        // 输出TTS录音到文件（支持WAV/MP3）
        public static void SaveToFile(string text, string filePath, int sampleRate = 44100,
                                   int bitsPerSample = 16, int channels = 1, string format = "wav")
        {
            // 1. 生成PCM流
            // 生成内存流
            var memoryStream = GenerateAudioStream(text, sampleRate, bitsPerSample, channels);

            // 2. 转换为目标格式
            using (var reader = new RawSourceWaveStream(memoryStream, new WaveFormat(sampleRate, bitsPerSample, channels)))
            {
                switch (format.ToLower())
                {
                    case "mp3":
                        using (var writer = new LameMP3FileWriter(filePath, reader.WaveFormat, LAMEPreset.VBR_90))
                        {
                            reader.CopyTo(writer);
                        }
                        break;

                    case "wav":
                        WaveFileWriter.CreateWaveFile(filePath, reader);
                        break;
                }
            }
        }
    }
}

/*
 // 播放语音（24kHz, 16bit, 单声道）
NAudioTTSPlayer.PlayText("Hello, this is NAudio TTS playback", 24000, 16, 1);

// 保存为WAV文件（44.1kHz, 16bit, 立体声）
NAudioTTSPlayer.SaveToFile("This will be saved as WAV", "output.wav", 
                         sampleRate: 44100, bitsPerSample: 16, channels: 2, format: "wav");

// 保存为MP3文件（48kHz, 高质量）
NAudioTTSPlayer.SaveToFile("This will be an MP3", "output.mp3",
                         sampleRate: 48000, format: "mp3");
 */
